<template>
    <div class="white-box">
        <div class="table-mb">
            <el-button type="primary" @click="addClass">添加</el-button>
        </div>

        <!-- row-key="cate_id" 开启二级分类 -->
        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
        >
            <!-- <el-table-column prop="index" width="55"></el-table-column> -->
            <el-table-column prop="cate_id" label="分类ID" min-width="120"></el-table-column>
            <el-table-column prop="title" label="分类名称" min-width="200"></el-table-column>
            <el-table-column label="特惠" width="200">
                <template #default="{ row }">
                    <span>{{ row.special_offer == 1 ? "特惠" : "非特惠" }}</span>
                </template>
            </el-table-column>
            <el-table-column label="属性" min-width="360">
                <template #default="{ row }">
                    <span>{{ row.product_attribute }}</span>
                </template>
            </el-table-column>
            <el-table-column label="排序" width="240">
                <template #default="{ row }">
                    <el-input
                        v-model.trim="row.order_by"
                        clearable
                        placeholder="请输入排序数字"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        @change="() => inputSort(row)"
                        style="width: 100px"
                    />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <el-button class="theme-btn" link type="primary" @click="clickEdit(row)">编辑 </el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickDel(row)">
                        <template #reference>
                            <el-button class="theme-btn" link type="primary">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>

        <!-- 添加/编辑 -->
        <el-dialog
            v-model="dialogClass"
            :title="classType == 1 ? '添加分类' : '编辑分类'"
            width="640px"
            :append-to-body="true"
            :destroy-on-close="true"
            :close-on-click-modal="false"
            @close="closeAddClass"
        >
            <el-form ref="ruleClassRef" :model="ruleClassForm" :rules="ruleCheckClass" label-width="120px">
                <el-form-item label="上级分类" prop="cate_id">
                    <el-select v-model="ruleClassForm.cate_id" placeholder="请选择上级分类" @change="changeclassType" :disabled="classType == 2">
                        <el-option :label="item.title" :value="item.cate_id" v-for="(item, index) in class_options" :key="item.cate_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分类名称" prop="name">
                    <el-input v-model.trim="ruleClassForm.name" clearable placeholder="请输入分类名称" />
                </el-form-item>
                <el-form-item label="关联商品属性" prop="attrs_id">
                    <el-checkbox-group v-model="ruleClassForm.attrs_id">
                        <el-checkbox :label="item.attr_id" v-for="item in attr_options" :key="item.attr_id">
                            {{ item.attr_name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="特惠" prop="special_status">
                    <el-switch
                        v-model="ruleClassForm.special_status"
                        inline-prompt
                        size="large"
                        :active-value="1"
                        :inactive-value="0"
                        active-text="是"
                        inactive-text="否"
                    />
                </el-form-item>
                <el-form-item label="排序" prop="sort" required>
                    <el-input v-model.number="ruleClassForm.sort" clearable oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入排序数字" />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 30px">
                        <el-button type="primary" :loading="form_loading" @click="submitClassForm(ruleClassRef)">
                            {{ classType == 1 ? "确认添加" : "确认修改" }}
                        </el-button>
                        <el-button @click="resetClassForm(ruleClassRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <go-back></go-back>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, watch } from "vue"
import OneLoad from "@mixins/one-load"
import GoBack from "@components/GoBack.vue"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getList()
})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, pubParams, getdata } = OneLoad()

// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})
function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
    }
    getdata("product/cate/index", params)
}

/**
 * 添加/编辑
 * @property {Boolean} dialogClass 添加/编辑弹窗状态
 * @property {Boolean} form_loading 提交按钮状态
 * @property {Number} classType 弹窗类型，1是添加，2是编辑
 * @property {Array} ruleClassRef 表单规则
 * @property {Object} ruleClassForm  表单字段
 * @property {Object} ruleCheckClass  表单提示
 * @property {Function} submitClassForm 提交表单
 * @property {Function} addClass 添加分类
 * @property {Function} closeAddClass 关闭弹窗
 */
const dialogClass = ref(false)
const form_loading = ref(false)
const classType = ref(1)
const ruleClassRef = ref(null)
const ruleClassForm = reactive({
    sub_cate_id: null,
    cate_id: 0,
    name: "",
    sort: "100",
    special_status: 0, // [0:非特惠,1:特惠]
    attrs_id: [], // 属性集合
})
const ruleCheckClass = reactive({
    cate_id: [{ required: true, message: "请选择上级分类", trigger: "change" }],
    name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
    attrs_id: [{ type: "array", required: true, message: "请勾选关联商品属性", trigger: "change" }],
    sort: [{ required: true, message: "请输入排序数字", trigger: "blur" }],
})
const submitClassForm = (formEl) => {
    // 确认
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                title: ruleClassForm.name,
                special_offer: ruleClassForm.special_status,
                order_by: ruleClassForm.sort,
                attr_ids: ruleClassForm.attrs_id,
            }
            if (classType.value == 1) {
                data.parent_id = ruleClassForm.cate_id
            } else {
                data.cate_id = ruleClassForm.sub_cate_id
            }

            let url = classType.value == 1 ? "product/cate/add" : "product/cate/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogClass.value = false
                        proxy.$message({ message: `${classType.value == 1 ? "添加成功！" : "编辑成功！"}`, type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetClassForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const addClass = () => {
    dialogClass.value = true
    classType.value = 1
    getClass()
}
const closeAddClass = () => {
    dialogClass.value = false
    resetClassForm(ruleClassRef.value)
}
const changeclassType = (value) => {
    ruleClassForm.type = value
}
// 编辑
const clickEdit = (row) => {
    dialogClass.value = true
    classType.value = 2
    getClass()
    getEditDetail(row.cate_id)
    setTimeout(() => {
        ruleClassForm.name = row.title
        ruleClassForm.sort = row.order_by
        ruleClassForm.cate_id = row.parent_id
        ruleClassForm.sub_cate_id = row.cate_id
        ruleClassForm.special_status = Number(row.special_offer)
    }, 50)
}
function getEditDetail(id) {
    proxy.$axios
        .get("product/cate/update", {
            params: {
                cate_id: id,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                result.map((item) => {
                    item.selected == 1 && ruleClassForm.attrs_id.push(item.attr_id)
                })
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
// 删除
function clickDel(row) {
    proxy.$axios
        .post("product/cate/delete", {
            cate_id: row.cate_id,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 排序
const inputSort = (row) => {
    if (!row.order_by) {
        proxy.$message({ message: "请输入排序数字", type: "warning" })
        return
    }
    proxy.$axios
        .post("product/cate/sort", {
            cate_id: row.cate_id,
            order_by: row.order_by,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 获取分类、商品属性
const class_options = ref([])
const attr_options = ref([])
function getClass() {
    proxy.$axios
        .get("product/cate/add")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                if (result.cate_list) {
                    result.cate_list.unshift({
                        cate_id: 0,
                        title: "顶级分类",
                    })
                }
                class_options.value = result.cate_list
                attr_options.value = result.attr_list
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "GoodsClass",
}
</script>

<style lang="less" scoped>
:deep(.el-table__row--level-1) {
    background: @gray-1;
}

.prize-upload {
    display: flex;

    :deep(.el-upload--picture-card) {
        width: 100px !important;
        height: 100px !important;
    }

    :deep(.el-upload-list__item) {
        width: 100px !important;
        height: 100px !important;
    }
}
</style>
